<?php
require_once('db.php');



function sales_summary(){

	$sEcho			=	$_POST['sEcho'];
	$iDisplayStart	=	$_POST['iDisplayStart'];
	$iDisplayLength	=	$_POST['iDisplayLength'];
	$sort_by		=	$_POST['iSortCol_0'];
	$nm_kolom		=	array('bill_id','tot_item','total','tax','discount','grand_tot');
	$cari			=	$_POST['sSearch'];
	$sSortDir_0		=	$_POST['sSortDir_0'];
	
	
	$get_all_data	=	get_data_all($sudin,$type);
	$iTotalRecords	=	@mysql_num_rows($get_all_data);
	
	if ($type=="DOM0"){
	
		if (date("d")>15) {
			$total_hari	=	date("d") - 1 ;
		} else {
			$total_hari	=	date('t',strtotime('last month'));
		}
	
		$query ="select distinct nopd,nama,sudin,total_hari,tim_ts,order_date  from ts_order  where sudin like '%".$sudin."%' and total_hari>=$total_hari ";
	} else 
	if ($type=="DOM1") {
		if (date("d")>15) {
			$total_hari	=	date("d") - 2 ;
		} else {
			$total_hari	=	date('t',strtotime('last month'))-1;
		}
		$query ="select distinct nopd,nama,sudin,total_hari,tim_ts,order_date  from ts_order  where sudin like '%".$sudin."%' and total_hari=$total_hari ";
	} else 
	if ($type=="DOM2") {
		if (date("d")>15) {
			$total_hari	=	date("d") - 3 ;
		} else {
			$total_hari	=	date('t',strtotime('last month'))-2;
		}
		$query ="select distinct nopd,nama,sudin,total_hari,tim_ts,order_date  from ts_order  where sudin like '%".$sudin."%' and total_hari=$total_hari  ";
	} else 
	if ($type=="DOM3") {
		if (date("d")>15) {
			$total_hari	=	date("d") - 4 ;
		} else {
			$total_hari	=	date('t',strtotime('last month'))-3;
		}
		$query ="select distinct nopd,nama,sudin,total_hari,tim_ts,order_date  from ts_order  where sudin like '%".$sudin."%' and total_hari<=$total_hari ";
	}
	
	if(!empty($cari)){
		$query .="  and nama like '%".$cari."%'";
	}
	$query .=" order by ".$nm_kolom[$sort_by]." ".$sSortDir_0;
	$query .=" limit ".$iDisplayStart.",".$iDisplayLength;
	
	$res=mysql_query($query,$link);
	while($data_get=@mysql_fetch_array($res)){
		$data_arr[]=array($data_get['nopd'],$data_get['nama'],$data_get['sudin'],$data_get['total_hari'],$data_get['tim_ts'],$data_get['order_date'],"DT_RowId"=>"td_".$data_get['nopd']);
	}
	$data_json=array('sSudin'=>$sudin,'sEcho'=>$sEcho,'iTotalRecords'=>$iTotalRecords,'iTotalDisplayRecords'=>$iTotalRecords,'aaData'=>$data_arr);
	return json_encode($data_json);
}


echo sales_summary();
?>